import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_hotwork/home/Home.dart';
import 'package:flutter_hotwork/mine/Mine.dart';
import 'package:flutter_hotwork/tongxunlu/tongxunlu.dart';
import 'package:flutter_hotwork/utils/LogUtil.dart';
import 'package:flutter_hotwork/xunjian/XunJianControl.dart';
import 'package:flutter_hotwork/xunjian/XunJianMap.dart';
import 'package:flutter_hotwork/xunjian/XunJianTaskList.dart';
import 'package:flutter_hotwork/zhifa/QuestionUpList.dart';
import 'package:logger/logger.dart';
import 'EventBusUtils.dart';
import 'homepage/NavigationIconView.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';
import 'package:flutter_hotwork/Myapplication.dart';


/**
 * 主页
 */
class HomePage extends StatefulWidget {
  static const String routeName = '/material/bottom_navigation';

  @override
  HomePageState createState() => HomePageState();
}

class HomePageState extends State<HomePage> with TickerProviderStateMixin {

  //定位
  Map<String, Object> _loationResult;
  BaiduLocation _baiduLocation; // 定位结果
  StreamSubscription<Map<String, Object>> _locationListener;
  LocationFlutterPlugin _locationPlugin = new LocationFlutterPlugin();
  int firstlocation=0;
  int currentIndex = 0;
  BottomNavigationBarType type = BottomNavigationBarType.fixed;
  List<NavigationIconView> navigationViews;
  var body;
  List<Widget> Pages = [];

  @override
  void initState() {
    super.initState();
    navigationViews =  MyApplication.loginuserinfo.userInfo.amHotuser==0?<NavigationIconView>[
      NavigationIconView(
        activeIcon:  Image(height:40,width: 40,image: AssetImage('images/home.png')),
        icon:  Image(height:40,width: 40,image: AssetImage('images/home.png')),
        title: '首页',
        color: new Color.fromARGB(255, 0, 215, 198),
        vsync: this,
      ),
      NavigationIconView(
        activeIcon:  Image(height:40,width: 40,image: AssetImage('images/zhifa.png')),
        icon:  Image(height:40,width: 40,image: AssetImage('images/zhifa.png')),
        title: '故障',
        color: new Color.fromARGB(255, 0, 215, 198),
        vsync: this,
      ),
      NavigationIconView(
        activeIcon:  Image(height:40,width: 40,image: AssetImage('images/xunjian.png')),
        icon:  Image(height:40,width: 40,image: AssetImage('images/xunjian.png')),
        title: '巡检',
        color: new Color.fromARGB(255, 0, 215, 198),
        vsync: this,
      ),
      NavigationIconView(
        activeIcon:  Image(height:40,width: 40,image: AssetImage('images/tongxunlu.png')),
        icon:  Image(height:40,width: 40,image: AssetImage('images/tongxunlu.png')),
        title: '通讯录',
        color: new Color.fromARGB(255, 0, 215, 198),
        vsync: this,
      ),
      NavigationIconView(
//        activeIcon: const Icon(Icons.accessibility),
//        icon: const Icon(Icons.account_box),
        activeIcon:  Image(height:40,width: 40,image: AssetImage('images/wode.png')),
        icon:  Image(height:40,width: 40,image: AssetImage('images/wode.png')),
        title: '我的',
        color: new Color.fromARGB(255, 0, 215, 198),
        vsync: this,
      )
    ]:<NavigationIconView>[
      NavigationIconView(
        activeIcon:  Image(height:40,width: 40,image: AssetImage('images/home.png')),
        icon:  Image(height:40,width: 40,image: AssetImage('images/home.png')),
        title: '首页',
        color: new Color.fromARGB(255, 0, 215, 198),
        vsync: this,
      ),
      NavigationIconView(
//        activeIcon: const Icon(Icons.accessibility),
//        icon: const Icon(Icons.account_box),
        activeIcon:  Image(height:40,width: 40,image: AssetImage('images/wode.png')),
        icon:  Image(height:40,width: 40,image: AssetImage('images/wode.png')),
        title: '我的',
        color: new Color.fromARGB(255, 0, 215, 198),
        vsync: this,
      )
    ];

    for (NavigationIconView view in navigationViews)
      view.controller.addListener(rebuild);

    navigationViews[currentIndex].controller.value = 1.0;


    /// 动态申请定位权限
    _locationPlugin.requestPermission();
    /// 设置ios端ak, android端ak可以直接在清单文件中配置
    LocationFlutterPlugin.setApiKey("AATp1fIh3jcs3nUN4wglXGzG209ZQZap");
    _locationListener = _locationPlugin
        .onResultCallback()
        .listen((Map<String, Object> result) {
      setState(() {
        _loationResult = result;
        if (_loationResult != null) {

          _loationResult.forEach((key, value) {
            if(key == "latitude"){
              // print("地址latitude111"+value.toString());
              if(null==value){
                _startLocation();
              }
              MyApplication.latitude=value;
            }
            if(key == "locationDetail"){
              // print("地址详情111"+value.toString());
              if(null!=value){
                MyApplication.locationdetail=value;
              }

            }
            if(key == "longitude"){
              // print("地址location111"+value.toString());
              MyApplication.longitude=value;
            }
          });
        }
        try {
          _baiduLocation = BaiduLocation.fromMap(result); // 将原生端返回的定位结果信息存储在定位结果类中
//          print(_baiduLocation);
        } catch (e) {
          print(e);
        }
      });
    });



  }

  @override
  void dispose() {
    for (NavigationIconView view in navigationViews) view.controller.dispose();
    if (null != _locationListener) {
      _locationListener.cancel(); // 停止定位
    }
    bus.off("flush");
    super.dispose();
  }

  /// 设置android端和ios端定位参数
  void _setLocOption() {
    /// android 端设置定位参数
    BaiduLocationAndroidOption androidOption = new BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(2000); // 设置发起定位请求时间间隔

    Map androidMap = androidOption.getMap();

    /// ios 端设置定位参数
    BaiduLocationIOSOption iosOption = new BaiduLocationIOSOption();
    iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    iosOption.setBMKLocationCoordinateType("BMKLocationCoordinateTypeBMK09LL"); // 设置返回的位置坐标系类型
    iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
    iosOption.setLocationTimeout(10); // 设置位置获取超时时间
    iosOption.setDesiredAccuracy("kCLLocationAccuracyBest");  // 设置预期精度参数
    iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
    iosOption.setDistanceFilter(100); // 设置定位最小更新距离
    iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
    iosOption.setPauseLocUpdateAutomatically(false); //  定位是否会被系统自动暂停

    Map iosMap = iosOption.getMap();

    _locationPlugin.prepareLoc(androidMap, iosMap);
  }

  /// 启动定位
  void _startLocation() {
    if (null != _locationPlugin) {
      _setLocOption();
      _locationPlugin.startLocation();
    }
  }

  /// 停止定位
  void _stopLocation() {
    if (null != _locationPlugin) {
      _locationPlugin.stopLocation();
    }
  }

  void rebuild() {
    setState(() {
      // Rebuild in order to animate views.
    });
  }

  void initData() {
    body = new IndexedStack(
      children: MyApplication.loginuserinfo.userInfo.amHotuser==0?[
        new HomeScreen(),
        new GuzhangBaogaoScreen(),
        new XunJianControlScreen(),
        new TongxunluScreen(),
        new MineScreen()
      ]:[
        new HomeScreen(),
        new MineScreen()
      ],
      index: currentIndex,
    );
  }
  var bus = EventBus();
  @override
  Widget build(BuildContext context) {
    if(firstlocation == 0){
      _startLocation();
    }




    initData();
    final BottomNavigationBar botNavBar = BottomNavigationBar(
      items: navigationViews
          .map((NavigationIconView navigationView) => navigationView.item)
          .toList(),
      currentIndex: currentIndex,
      type: type,
      onTap: (int index) {
        if(index==1||index==2){
          bus.send("flush", "flush");
        }

        setState(() {
          navigationViews[currentIndex].controller.reverse();
          currentIndex = index;
          navigationViews[currentIndex].controller.forward();
        });
      },
    );

    return Scaffold(

      body: body,
      bottomNavigationBar: botNavBar,
//        drawer: new MyDrawer()
    );
  }


}
